import { langobj } from '@/utils/database'
import { cloneDeep, find, uniqBy, map} from 'lodash'



export const langTxt = (lang, lgid, list) => {
    let str = '';
    let obj = null;
   
    if(list && list.length > 0) { // 从list 中获取
        list.forEach((item)=>{
            if(item.id == lgid) {
                obj = item;
            }
        });
        if(obj) {
            if(lang == 1) {
                str = obj.en || '';
            } else if(lang == 2) {
                str = obj.zh || '';
            }
        }
    }
    // 
    if(!str && lgid < 0) {
        // 从 langobj 获取
        if(langobj[lgid]) {
            obj = langobj[lgid] || null;
        }
        if(obj) {
            if(lang == 1) {
                str = obj.en || '';
            } else if(lang == 2) {
                str = obj.zh || '';
            }
        }
    }
    return str;
}


export const isEmpty = (obj) => {
    if (!obj && obj !== 0) {
        return true
    }
    if (typeof obj === 'string') {
        return obj === ''
    } else if (obj instanceof Array) {
        return obj.length === 0
    }
    return false
}


// 防用户 开浏览器控制台
export const preventPeep = () => {
    let stime = 0;
    let etime = 0;
    setInterval(() => {
        stime = new Date().valueOf();
        debugger;
        etime = new Date().valueOf();
        if(etime - stime > 50) {
            window.location.href = window.location.origin;
        }
    }, 1000)
}


// 过滤处理 表头数据
export const getFilterThArr = (arr, key) => {
    let res = [];
     // ENG CHN
    let str = '';
    // let farr = [];
    let obj = null;
    arr.forEach((item)=>{
        // farr = [];
        obj = null;
        if(str.indexOf('**' + item.uiElCode + '**') < 0) {
            if(item.languageCode == 'ENG') {
                obj = find(arr, (o)=>{ return (o.uiElCode == item.uiElCode && o.languageCode == 'CHN')});
            } else {
                obj = find(arr, (o)=>{ return (o.uiElCode == item.uiElCode && o.languageCode == 'ENG')});
            }

            if(obj) {
                res.push({
                    dataCode: item.uiElCode,
                    label: item.uiElName,
                    langkey: key + '_' + item.uiElCode,
                    en: item.languageCode == 'ENG' ? item.uiElName : obj.uiElName,
                    zh: item.languageCode == 'CHN' ? item.uiElName : obj.uiElName,
                    uiElDefSelect: item.uiElDefSelect,
                    columnWidth: item.columnWidth
                });
                str += '**' + item.uiElCode + '**';
            }
        }
    });
    return res;
};
// 过滤处理 表头数据
export const getFilterLangArr = (arr) => {
    return map(arr, (o)=> {
        return {
            id: o.langkey,
            en: o.en,
            zh: o.zh
        }
    });
}

export const geneMathHash = (str,caseSensitive) => {
    if(!caseSensitive){
        str = str.toLowerCase();
    }
    var hash  =   1315423911,i,ch;
    for (i = str.length - 1; i >= 0; i--) {
        ch = str.charCodeAt(i);
        hash ^= ((hash << 5) + ch + (hash >> 2));
    }
    return  (hash & 0x7FFFFFFF);
};

//计算等n边形坐标
export const calculateEquilateralTriangleCoords = (sideLength, n) =>{
const vertices = [];
for (let i = 1; i <= n; i++) {
    const angleRadians = (i - 1) * 2 * Math.PI / n;
    const x = sideLength * Math.cos(angleRadians);
    const y = sideLength * Math.sin(angleRadians);
    vertices.push({ x, y });
}
return vertices;
}

export const  saveImageWithWhiteBackground = (imageElement, imageName) => {
    // 创建一个canvas元素
    var canvas = document.createElement('canvas');
    canvas.width = imageElement.width;
    canvas.height = imageElement.height;

    // 获取canvas的2D上下文
    var ctx = canvas.getContext('2d');

    // 将背景填充为白色
    ctx.fillStyle = '#FFFFFF';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 绘制图片
    ctx.drawImage(imageElement, 0, 0);

    // 获取图片数据
    var imgData = canvas.toDataURL('image/png');

    // 创建一个a标签模拟点击来下载图片
    var downloadLink = document.createElement('a');
    downloadLink.href = imgData;
    downloadLink.download = imageName || 'downloadedImage.png';
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
}

export const saveImgDiv = (id) => {
    var divContent = document.getElementById(id).innerHTML; 
    console.log(divContent)
    var data = "data:image/svg+xml," + 
    "<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'>" + 
    "<foreignObject width='100%' height='100%'>" + 
    "<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:16px;font-family:Helvetica'>" + 
    divContent + 
    "</div>" + 
    "</foreignObject>" + 
    "</svg>"; 
    var img = new Image(); 
    img.src = data; 
    var canvas = document.createElement("canvas"); 
    var ctx =  canvas.getContext("2d"); 
    img.crossOrigin="anonymous"; 
    img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>"; 
    ctx.drawImage(img, 0, 0); 
    var canvasbase = canvas.toDataURL(); 
    // 创建一个a标签模拟点击来下载图片
    var downloadLink = document.createElement('a');
    downloadLink.href = canvasbase;
    downloadLink.download = (new Date().getTime() + '.png') || 'downloadedImage.png';
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
}
// export const createExcel = (data, name) => {
//     let tmp = [data[0]];
//     const header = tmp.map((item) => {
//         let result = "";
//         for (const key in item) {
//             result += key + ",";
//         }
//         return result;
//     }).join("\n");
	
//     const table = header + '\n' + data.map((item) => {
//             let result = "";
//             for (const key in item) {
//                 if(item[key] != null) {
//                     item[key] = item[key].toString().replace(/,/gi, "，")
//                 }
//                 result += item[key] + ",";
//             }
//             return result;
//         }).join("\n");
//     //encodeURIComponent解决中文乱码
//     let uri = "data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(table);
//     //通过创建a标签实现
//     var link = document.createElement("a");
//     link.href = uri;
//     //对下载的文件命名
//     link.download = name + ".csv";
//     document.body.appendChild(link);
//     link.click();
//     document.body.removeChild(link);
// }

export const createExcel = (data,name) => {
    if (!data) {
      console.log('下载失败，解析数据为空！')
      return
    }
    // 创建一个新的url，此url指向新建的Blob对象
    // let url = window.URL.createObjectURL(new Blob([data]))
    let url = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(data);
    // 创建a标签，并隐藏改a标签
    let link = document.createElement('a')
    link.style.display = 'none'
    // a标签的href属性指定下载链接
    link.href = url
    //setAttribute() 方法添加指定的属性，并为其赋指定的值。
    link.setAttribute('download', name)
    document.body.appendChild(link)
    link.click()
    link.remove();
  }

  export const creatTxt = (data, name) => {
    const blob = new Blob([data], {type: 'text/plain'});
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = name;
    link.click();
    link.remove();
  }

  export const computedgraphOptions = (titleTxt, titleSubtxt, data, showDown, titleLeft, legendPosition, dataPosition, downloadTxt, lengendWi, legendTop) => {
    let option = {
		title: {
			text: titleTxt,
			subtext: titleSubtxt,
			left: titleLeft || '10%',
            textStyle: {
                fontSize: 14,
                overflow: 'truncate', // 文本溢出时显示省略标记
                ellipsis: '...', // 指定折行后的省略符号
            },
            // 或者使用autoEllipsis选项，当文本超出容器时自动折行
            autoEllipsis: true,
		},
        toolbox: {
            show: false,
            iconSize: 30,
            itemSize: 20,
            itemGap: 30,
            left: 'right', // 可以是像素值或者百分比，例如 '20%'
            top: 'top',   
            feature: {
                saveAsImage: {
                    title: downloadTxt || 'Download', //controlSto.language == 1 ? 'Download' : '下载'
                    color: '#333333',
                    pixelRatio: 2,
                    width: 30,
                    icon: 'image://',
                    emphasis: {
                        iconStyle: {
                            color: '#ffffff',
                            textBackgroundColor: 'rgba(0, 0, 0, 0.8)',
                            textBorderRadius: 2,
                            textPadding: 5,
                            borderWidth: 30
                        }
                    },
                    iconStyle: {
                        iconSize: 30,
                    }
                }
            }
        },
		tooltip: {
			trigger: 'item',
            formatter: (param) => {
                return  `<div style="max-width: 300px;white-space: pre-wrap">${param.data.name} : ${param.data.value}%</div>`
            }
		},
		legend: {
            // show: false,
			top: 'center',
			left: legendPosition || '60%',
            bottom: '10%',
            top: legendTop || '18%',
            height: "170",
            // right: 0,
			icon: 'circle',
			orient: 'vertial',
            itemWidth: 10,
            tooltip: {
                show: true,
                trigger: 'item',//鼠标移动上去展示全称
            }, 
            textStyle: {
                fontSize: 12
            },
            itemGap: 10,
            formatter: function(value) {
                // 如果标签长度超过15，将剩余的文字替换为省略号
                if (lengendWi) {
                    if (value.length > 10) {
                        return value.slice(0, 14) + '...';
                    } else {
                        return value;
                    }
                } else  {
                    if (value.length > 6) {
                        return value.slice(0, 7) + '...';
                    } else {
                        return value;
                    }
                }
                
            }
		},
		series: [
			{
				name: '',
				type: 'pie',
				radius: '50%',
				data: data,
                center: dataPosition || ['30%', '50%'],
				emphasis: {
					itemStyle: {
						shadowBlur: 10,
						shadowOffsetX: 0,
						shadowColor: 'rgba(0, 0, 0, 0.5)'
					}
				},
				label: {
					show: true,
					position: "inside",
					formatter: '{c}%'
				}
			}
		]
	}
    return option;
  }
